/*
Author: Dave Lenz
Creation date: 23 jun 2009
 */
package nl.ypmits.utils.as3.bitmap.bitmaplayers {
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;

	public class BitmapLayersProto extends Sprite {
		private var bm : BitmapLayersVO;
		public static const READY : String = "ready";
		public var items : Array = [];

		public function BitmapLayersProto( bm : BitmapLayersVO ) 
		{
			this.bm = bm;
			
			addEventListener( Event.ADDED_TO_STAGE, init );
		}

		
		private function init(event : Event) : void 
		{
			var clr : uint;
			var brightness : Number;
			var c : BitmapParticle;
			var w : int = bm.bitmapdata.width;
			var h : int = bm.bitmapdata.height;
			for(var i : int = 0; i < w ; i += bm.everyPixelNum ) 
			{
				for(var j : int = 0; j < h ; j += bm.everyPixelNum ) 
				{
					bm.useColor ? clr = bm.bitmapdata.getPixel32( i, j ) : clr = bm.color;
					brightness = bm.bitmapdata.getPixel( i, j ) / 0xFFFFFF;
					if(brightness < 1 && brightness > 0) 
					{
						c = new BitmapParticle( bm );
						c.drawCircle( 0, 0, brightness, clr );
						c.x = i;
						c.y = j;
						items.push( c );
						addChild( c );
					}
				}
			}
			dispatchEvent( new Event( BitmapLayersProto.READY ) );
		}

		
		public function setBackgroundToMask( bitmap : Bitmap ) : void 
		{
			trace( "BitmapLayersProto.setBackgroundToMask(" + [ bitmap ] + ")" );
			for (var i : int = 0; i < items.length ; i++) 
			{
				if( items[i].width > 1 ) 
				{
					var c : BitmapParticle = BitmapParticle( items[i] );
				
					var r : Rectangle = c.getBounds( this );
					var bmd : BitmapData = new BitmapData( r.width, r.height);
					//var nr : Rectangle = new Rectangle(0, 0, r.width, r.height );
					var m : Matrix = new Matrix();
					m.tx = r.x;
					m.ty = r.y;
					bmd.draw( bitmap, m, null, null, r, false );
					
					var b : Bitmap = new Bitmap( bmd );
					b.x = r.x;
					b.y = r.y;
					addChild( b );
					
					c.setBitmap( b );
					
				} else {
					
				}
			}
		}
	}
}